<?php

namespace app\api\service\recharge;

use app\api\service\Basics;
use app\api\model\User as UserModel;
use app\api\model\recharge\Order as OrderModel;
//use app\api\model\WxappPrepayId as WxappPrepayIdModel;
use app\api\model\user\BalanceLog as BalanceLogModel;

//use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\enum\recharge\order\PayStatus as PayStatusEnum;

// use app\api\model\Order as GoodsOrderModel;
use app\api\service\order\Checkout as CheckoutModel;
use app\api\validate\order\Checkout as CheckoutValidate;
use \think\Db;

class PaySuccess extends Basics
{
    // 订单模型
    public $model;

    // 当前用户信息
    private $user;

    /**
     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo)
    {
        // 实例化订单模型
        $this->model = OrderModel::getPayDetail($orderNo);
        $this->wxappId = $this->model['wxapp_id'];
        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);
    }

    /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }

    /**
     * 订单支付成功业务处理 mmmodify，充值订单支付回调
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    public function onPaySuccess($payType, $payData)
    {
        return $this->model->transaction(function () use ($payType, $payData) {
            // 更新订单状态
            $this->model->save([
                'pay_status' => PayStatusEnum::SUCCESS,
                'pay_time' => time(),
                'transaction_id' => $payData['transaction_id']
            ]);
            // 累积用户余额
            $this->user->setInc('balance', $this->model['actual_money']);
            // 用户余额变动明细
            BalanceLogModel::add(SceneEnum::RECHARGE, [
                'user_id' => $this->user['user_id'],
                'money' => $this->model['actual_money'],
                'wxapp_id' => $this->wxappId,
            ], ['order_no' => $this->model['order_no']]);
            // 更新prepay_id记录
            if ($payType == PayTypeEnum::WECHAT) {
				//WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::RECHARGE);
            }
			
			// 充值后分销分钱 mmmodify  充值成功后，返佣送商品
			// $secondUobj = Db::name('recharge_order')->where('order_id'=>$userId, $this->user['user_id'])->find();
			// 分销上3级分销充值返佣
			$this->inmoney();
			// 充值赠送商品或项目
			$this->giftTheGood();
			
            return true;
        });
    }
	
	// 测试小程序充值成功，mmmodify，前端点击按钮，调用充值成功后的回调接口，测试函数如下
	public function onPaySuccess222($payType, $payData){
		// 每次测试，需要将订单中的pay_status设置为10，才能触发事务机制 mmmodify
		// 正式环境需要将以下两步操作写到事务中
		// 分销上3级分销充值返佣
		// $this->inmoney();
		// // 充值赠送商品或项目
		// $this->giftTheGood();
		// exit;
		
		
		return $this->model->transaction(function () use ($payType, $payData) {
			// 更新订单状态
			$this->model->save([
				'pay_status' => PayStatusEnum::SUCCESS,
				'pay_time' => time(),
				'transaction_id' => $payData['transaction_id']
			]);
			// 累积用户余额
			$this->user->setInc('balance', $this->model['actual_money']);
			// 用户余额变动明细d
			BalanceLogModel::add(SceneEnum::RECHARGE, [
				'user_id' => $this->user['user_id'],
				'money' => $this->model['actual_money'],
				'wxapp_id' => $this->wxappId,
			], ['order_no' => $this->model['order_no']]);
			// 更新prepay_id记录
			if ($payType == PayTypeEnum::WECHAT) {
				//WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::RECHARGE);
			}
			// 充值后分销分钱 mmmodify  本地支付回调模拟
			// 分销上3级分销充值返佣
			$this->inmoney();
			// 充值赠送商品或项目
			$this->giftTheGood();
			
			return true;
		});
	}
	
	// 用户充值函数
	public function inmoney(){
		$userId = $this->model['user_id'];
		$firstUobj = Db::name('dealer_referee')->where(['user_id'=>$userId, 'level'=>1])->find();
		if($firstUobj){
			$firstMoney = $this->model['pay_price'] * ($this->model['fxzhe1'] * 0.01);
			$this->inmoneyFun($firstMoney, $firstUobj);
		}
		$secondUobj = Db::name('dealer_referee')->where(['user_id'=>$userId, 'level'=>2])->find();
		if($secondUobj){
			$secondMoney = $this->model['pay_price'] * ($this->model['fxzhe2'] * 0.01);
			$this->inmoneyFun($secondMoney, $secondUobj);
		}
		$thirdUobj = Db::name('dealer_referee')->where(['user_id'=>$userId, 'level'=>3])->find();
		if($thirdUobj){
			$thirdMoney = $this->model['pay_price'] * ($this->model['fxzhe3'] * 0.01);
			$this->inmoneyFun($thirdMoney, $thirdUobj);
		}
	}
	public function inmoneyFun($firstMoney, $firstUobj){
		$firstMoney && Db::name('dealer_user')->where('user_id',$firstUobj['dealer_id'])->setInc('money', $firstMoney);
		$firstMoney && Db::name('dealer_capital')->insert([
			'user_id' => $firstUobj['dealer_id'],
			'flow_type' => 10,
			'money' => $firstMoney,
			'describe' => '充值佣金结算',
			'wxapp_id' => $this->model['wxapp_id'],
			'create_time' => time(),
			'update_time' => time()
		]);
	}
	
	// 为用户赠送商品，订单入库，用户金额不扣，商品信息修改
	public function giftTheGood(){
		$giftGoodid = $this->model['gift_goodid'];
		if($giftGoodid > 0){
			// 只支持单个规格的商品，而且只查询了单条规格
			$goodObj = Db::name('goods')->where(['goods_id'=>$giftGoodid])->find();
			$skuidObj = Db::name('goods_sku')->where(['goods_id'=>$giftGoodid])->find();
			$imgeObj = Db::name('goods_image')->where(['goods_id'=>$giftGoodid])->find();
			$goodObj['goods_sku'] = $skuidObj;
			$goodObj['image'] = $imgeObj;
			
			$this->giftGoodFun($this->user, $goodObj, $this->model['wxapp_id']);
			// 实例化结算台服务，需要新的结算服务
			// $Checkout = new CheckoutModel;
			// $orderInfo = $Checkout->onCheckout222($this->user, $goodObj, $this->model['wxapp_id']);
		}
	}
	
	// 送商品函数
	private function giftGoodFun($user, $goodObj, $wxappid){
		// $this->user = $user;
		
		// 订单商品总数量
		$orderTotalNum = 1;

		$allPayMoney = $goodObj['goods_sku']['goods_price'] * $orderTotalNum;
		
		$shopObj = Db::name('store_shop')->where(['wxapp_id'=>$wxappid])->find();
		$shopid = $shopObj['shop_id'];
		
		$userid = $user['user_id'];
		
		// 订单数据入库，不使用积分和优惠券，mmmodify
		$data = [
		    'user_id' => $user['user_id'],
		    'order_no' => date("Ymd").rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(1,9),
		    'total_price' => $allPayMoney,
		    'order_price' => $allPayMoney,
			
			'cons_type' => $goodObj['cons_type'],	// mmmodify
			'cons_num' => $goodObj['cons_num'],
		    'cons_lastnum' => $goodObj['cons_num'],
			
			'coupon_id' => 0,
		    'coupon_money' => 0.00,
		    'points_money' => 0.00,
		    'points_num' => 0,
		    'pay_price' => $allPayMoney,
		    'delivery_type' => 20,  // 线下消费自提
		    'pay_type' => 20,	// 微信支付
		    'buyer_remark' => '充值赠送',
		    'order_source' => 10,	// 普通订单
		    'order_source_id' => 0,	// 订单来源统一为0
		    'points_bonus' => 0,
		    'wxapp_id' => $wxappid,
			'create_time'=>time(),
			'update_time'=>time()
		];
		$data['pay_status'] = 20; //直接设置支付成功
		$data['pay_time'] = time();
		$data['transaction_id'] = '111222333';
		$data['express_price'] = 0;	// 运费金额
		$data['extract_shop_id'] = $shopid;
		
		// 保存订单记录
		$orderID = Db::name('order')->insertGetId($data);
		// 保存后获取保存的订单号
		
		// 订单拓展入库
		// 记录自提信息
		$linkObj = Db::name('user')->where('user_id', $userid)->find();
		Db::name('order_extract')->insert([
		    'linkman' => isset($linkObj['true_name']) ? $linkObj['true_name'] : '赠送',
		    'phone' => isset($linkObj['true_mobile']) ? $linkObj['true_mobile'] : '13888888888',
		    'user_id' => $userid,
		    'wxapp_id' => $wxappid,
			'order_id' => $orderID,
			'create_time'=>time(),
		]);
		
		// 订单中商品信息入库
		$item = [
		    'user_id' => $user['user_id'],
		    'wxapp_id' => $wxappid,
		    'goods_id' => $goodObj['goods_id'],
		    'goods_name' => $goodObj['goods_name'],
			'deduct_stock_type' => $goodObj['deduct_stock_type'],
			
		    'image_id' => $goodObj['image']['image_id'],
		    
		    'spec_type' => $goodObj['spec_type'],
		    'spec_sku_id' => $goodObj['goods_sku']['spec_sku_id'],
		    'goods_sku_id' => $goodObj['goods_sku']['goods_sku_id'],
		    'goods_attr' => '',
		    'content' => $goodObj['content'],
		    'goods_no' => $goodObj['goods_sku']['goods_no'],
		    'goods_price' => $goodObj['goods_sku']['goods_price'],
		    'line_price' => $goodObj['goods_sku']['line_price'],
		    'goods_weight' => $goodObj['goods_sku']['goods_weight'],
		    'is_user_grade' => 0,	// 是否存在会员折扣
		    'grade_ratio' => 0,
		    'grade_goods_price' => 0.00,
		    'grade_total_money' => 0.00,
		    'coupon_money' => 0.00,
		    'points_money' => 0.00,
		    'points_num' => 0,
		    'points_bonus' => 0,
		    'total_num' => $orderTotalNum,
		    'total_price' => $allPayMoney,
		    'total_pay_price' => $allPayMoney,
		    'is_ind_dealer' => 0,	// 是否开启分销
		    'dealer_money_type' => 10,	// 返利模式，10百分比，20固定金额
		    'first_money' => 0.00,
		    'second_money' => 0.00,
		    'third_money' => 0.00,
			'order_id' => $orderID,
			'create_time' => time()
		];
		$res2 = Db::name('order_goods')->insert($item);
		// echo '<pre>'; print_r($res2); exit;
		
		// 更新商品库存信息
		Db::name('goods')->where('goods_id',$goodObj['goods_id'])->setInc('sales_actual', 1);
		$upDD['goods_sales'] = $goodObj['goods_sku']['goods_sales']+1;
		$upDD['stock_num'] = $goodObj['goods_sku']['stock_num']-1;
		// echo '<pre>'; print_r($goodObj['goods_sku']); exit;
		$goods_sku_id = $goodObj['goods_sku']['goods_sku_id'];
		Db::name('goods_sku')->where('goods_sku_id',$goods_sku_id)->update($upDD);
	}

}